package com.boomsecret.utils;

import com.boomsecret.domain.Person;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by wangjinliang on 2018/1/5.
 */
public final class JacksonUtils {

    /**
     * @JsonIgnore 此注解用于属性上 作用是进行JSON操作时忽略该属性
     * @JsonFormat 此注解用于属性上 作用是把Date类型直接转化为想要的格式，如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")
     * @JsonProperty 此注解用于属性上 作用是把该属性的名称序列化为另外一个名称，如把trueName属性序列化为name，@JsonProperty("name")
     */

    private JacksonUtils() {}

    public final static ObjectMapper MAPPER;

    static {
        MAPPER = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    public static String serialize(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object deserialize(String jsonText, TypeReference type) {
        try {
            return MAPPER.readValue(jsonText, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T deserialize(String jsonText, Class<T> beanClass) {
        try {
            return MAPPER.readValue(jsonText, beanClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JsonNode deserialize(String jsonText) {
        try {
            return MAPPER.readTree(jsonText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        Person person = new Person(18, "tom");
        String personJson = JacksonUtils.serialize(person);
        System.out.println(personJson);

        Person newPerson = JacksonUtils.deserialize(personJson, Person.class);
        System.out.println(newPerson);

    }
}

